package jsu.hx.lost.Controller;

import jsu.hx.lost.Model.vo.PageResult;
import jsu.hx.lost.Service.AliyunOssService;
import jsu.hx.lost.Service.UserService;
import jsu.hx.lost.Model.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayOutputStream;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;
    @Autowired
    private AliyunOssService aliyunOssService;


    // 查询所有记录
    @GetMapping("/all")
    public List<User> getAllUsers() {
        return userService.getAllUsers();
    }

    // 注册用户
    @PostMapping("/register")
    public ResponseEntity<?> register(
            @RequestParam String password,
            @RequestParam String phone,
            @RequestParam String fullName) {
        return userService.register(password, phone, fullName);
    }
    @PostMapping("/admin/register")
    public ResponseEntity<?> adminRegister(
            @RequestParam String password,
            @RequestParam String phone,
            @RequestParam String fullName,
            @RequestParam String adminToken) {
        return userService.adminRegister(password, phone, fullName, adminToken);
    }
    // 根据ID查询
    @GetMapping("/byId/{id}")
    public ResponseEntity<?> getUserById(@PathVariable Long id) {
        User user = userService.getUserById(id);
        if (user == null) {
            return ResponseEntity.status(HttpStatus.NOT_FOUND).body("用户不存在");
        }

        // 拼接完整的 OSS 地址（假设 AliyunOssService 提供了 getBaseUrl 方法）
        String profileImage = aliyunOssService.getBaseUrl() + user.getProfileImage();
        user.setProfileImage(profileImage);

        return ResponseEntity.ok(user);
    }

    // 更新用户信息
    // UserController.java
    @PutMapping(value = "/update/{id}", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    public ResponseEntity<?> updateUser(
            @PathVariable Long id,
            @RequestPart(value = "avatar", required = false) MultipartFile avatarFile,
            @RequestParam(required = false) String username,
            @RequestParam(required = false) String password,
            @RequestParam(required = false) String fullName,
            @RequestParam(required = false) String gender,
            @RequestParam(required = false) String phone) {
        return userService.updateUser(id, avatarFile, username, password, fullName, gender, phone);
    }

    // 逻辑删除记录
    @DeleteMapping("delete/{id}")
    public String deleteUser(@PathVariable Long id) {
        return userService.deleteUser(id);
    }

    // 分页查询
    @GetMapping("/page")
    public ResponseEntity<PageResult<User>> getUsersByPage(
            @RequestParam int page,
            @RequestParam int pageSize,
            @RequestParam(required = false) String username,
            @RequestParam(required = false) String sortField,   // 新增排序字段参数
            @RequestParam(required = false) String sortOrder ) {
        PageResult<User> result = userService.getUsersByPage(page, pageSize, username,sortField,sortOrder);
        return ResponseEntity.ok(result);
    }
    // 导出查询后的用户数据
    @GetMapping("/export")
    public ResponseEntity<byte[]> exportUsersToExcel(
            @RequestParam(required = false) String username,
            @RequestParam(required = false) String sortField,
            @RequestParam(required = false) String sortOrder) {
        try {
            // 使用查询条件获取用户数据
            List<User> users = userService.getUsersByCondition(username, sortField, sortOrder);

            // 检查是否有数据
            if (users == null || users.isEmpty()) {
                return ResponseEntity.status(HttpStatus.NO_CONTENT)
                        .body("没有可导出的用户数据".getBytes());
            }

            // 调用 Service 层方法，将用户数据导出为 Excel
            ByteArrayOutputStream stream = userService.exportToExcel(users);

            // 设置响应头
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);

            // 对文件名进行编码处理
            String encodedFilename = URLEncoder.encode("用户数据.xlsx", StandardCharsets.UTF_8.name());
            headers.setContentDispositionFormData("attachment", encodedFilename);

            return new ResponseEntity<>(stream.toByteArray(), headers, HttpStatus.OK);
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(("导出失败: " + e.getMessage()).getBytes());
        }
    }
    // 添加导入方法
    @PostMapping("/import")
    public ResponseEntity<Map<String, Object>> importUsersFromExcel(@RequestParam("file") MultipartFile file) {
        try {
            Map<String, Object> result = userService.importFromExcel(file);
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            Map<String, Object> response = new HashMap<>();
            response.put("status", "error");
            response.put("message", "导入失败: " + e.getMessage());
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(response);
        }
    }
}